// service/cleaner/cmd/main.go
package main

import (
	"os"
	"os/signal"
	"syscall"
	"time"
	"yunpan/db"
	"yunpan/logger"
	"yunpan/pool"
    "yunpan/service/cleaner/internal"
	"go.uber.org/zap"
)

func main() {
	// 初始化日志系统
	logger.InitLoggerWithPath("logs/cleaner", "cleaner.log")
	defer logger.Log.Sync()
	defer logger.Api.Sync()

	logger.Info("Cleaner service starting...")

	// 初始化数据库连接
	if err := db.InitDB(); err != nil {
		logger.Fatal("Failed to initialize database", zap.Error(err))
	}
	logger.Info("Database connection initialized")

	// 初始化工作池
	dbPool := pool.NewDBWorkerPool(5, 100)
	cephPool := pool.NewCephWorkerPool(10, 100)

	dbPool.Start()
	cephPool.Start()
	defer dbPool.Stop()
	defer cephPool.Stop()
	logger.Info("Worker pools started")

	// 计算到下一个0点的时间
	now := time.Now()
	next := time.Date(now.Year(), now.Month(), now.Day()+1, 0, 0, 0, 0, now.Location())
	duration := next.Sub(now)

	// 创建并启动文件清理器
	cleaner := internal.NewTrashCleaner(
		dbPool,
		cephPool,
		24*time.Hour, // 每24小时执行一次
		10,           // 保留10天
		100,          // 每批处理100个文件
	)

	// 等待到0点再开始第一次清理
	logger.Info("Waiting for first cleanup",
		zap.Time("currentTime", now),
		zap.Time("nextCleanup", next),
		zap.Duration("waitDuration", duration))

	time.Sleep(duration)
	cleaner.Start()

	logger.Info("Cleaner service started",
		zap.Int("retentionDays", 10),
		zap.Int("batchSize", 100))

	// 等待中断信号
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	// 优雅关闭
	cleaner.Stop()
	logger.Info("Cleaner service stopped gracefully")
}
